﻿using AutoMapper;
using MediatR;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using RedDragon.Common.Domain.Enterprise;
using RedDragon.Common.Domain.MaterialPlanning;
using RedDragon.Common.Domain.Supplier;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.ErroCodeEnum;
using SqlSugar;
using System.Globalization;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.MaterialPlanning
{
    /// <summary>
    /// 导入物料需求计划信息Handler
    /// </summary>
    public class ImportPlanHandler : IRequestHandler<ImportPlanCommand, Result>
    {
        /// <summary>
        /// mapper
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 物料需求计划表仓储
        /// </summary>
        public readonly IBaseRepository<Plan> planrepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<ImportPlanHandler> logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="planrepository"></param>
        /// <param name="logger"></param>
        public ImportPlanHandler(IMapper mapper, IBaseRepository<Plan> planrepository, ILogger<ImportPlanHandler> logger)
        {
            this.mapper = mapper;
            this.planrepository = planrepository;
            this.logger = logger;
        }

        /// <summary>
        /// 导入物料需求计划信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(ImportPlanCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Search };
            try
            {
                //获取文件扩展名 判断上传文件的类型是否正确
                var ext = Path.GetExtension(request.file.FileName);
                if (ext == ".xls" || ext == ".xlsx")
                {

                }
                else
                {
                    result.Msg = "您上传的文件类型不正确";
                    return result;
                }

                using (MemoryStream ms = new MemoryStream())
                {
                    request.file.CopyTo(ms);
                    ms.Position = 0;

                    //根据文件扩展名创建对应的工作簿对象(HSSFWorkbook用于.xls，XSSFWorkbook用于.xlsx)
                    IWorkbook wb = null;
                    if (ext == ".xls")//创建97-2003
                    {
                        wb = new HSSFWorkbook(ms);
                    }
                    else//创建2007及以上版本
                    {
                        wb = new XSSFWorkbook(ms);
                    }

                    //获取sheet 获取工作薄中的第一个工作表
                    ISheet sheet = wb.GetSheetAt(0);

                    int totalRows = sheet.LastRowNum;//总行数
                    int totalCells = sheet.GetRow(0).LastCellNum;//总列数

                    //创建一个用于从初解析后的数据的列表
                    var planList = new List<Plan>();

                    //循环总行数 开头必须是1 不然从表头开始添加
                    for (int i = 1; i <= totalRows; i++)
                    {
                        //获取当前行
                        IRow row = sheet.GetRow(i);

                        //这个类必须写到循环里边 不然只能添加一行
                        var dto = new Plan();//在循环内创建新的实例
                        //日期转换
                        //日期在excel表中必须是年月日格式 但不能加时分秒 (注意!!!!)
                        string inputDate = row.GetCell(6).ToString();
                        string[] multipleFormats = { "dd-M月-yyyy", "yyyy-M-dd" };
                        DateTime parsedDate;
                        foreach (var format in multipleFormats)
                        {
                            if (DateTime.TryParseExact(inputDate, new[] { format }, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate))
                            {
                                dto.CreatedTime = Convert.ToDateTime(parsedDate.ToString("yyyy-MM-dd"));
                                break;//成功解析后跳出循环
                            }
                        }
                        //下标从0开始 导入时 外键需进行判断
                        dto.PlanCode = row.GetCell(0).ToString();
                        dto.PlanName = row.GetCell(1).ToString();
                        dto.PlanDec = row.GetCell(12).ToString();
                        dto.SingleMaker = row.GetCell(13).ToString();
                        dto.CreatedOwner = row.GetCell(5).ToString();
                        dto.IsStatus = row.GetCell(2).ToString() == "新增" ? 1 : 2;
                        dto.AuditStatus = row.GetCell(4).ToString() == "未提交" ? 1 : 2;
                        dto.DepartmentId = 1;
                        //是否删除默认赋值 未删除
                        dto.IsDel = 1;
                        //将数据添加到数据集合中
                        planList.Add(dto);
                    }
                    //跳出循环后 使用AddRange进行批量添加
                    var res = planrepository.AddRange(planList);

                    //判断是否添加成功
                    if (res > 0)
                    {
                        result.Code = (int)CommonErrorCode.Success;
                        result.Msg = "导入物料需求计划成功";
                    }
                    else
                    {
                        result.Msg = "导入物料需求计划失败";
                    }
                }
            }
            catch (Exception ex)
            {
                result.Msg = "导入物料需求计划异常" + ex.Message;
                logger.LogError("导入物料需求计划异常" + ex.Message);
            }
            return result;
        }
    }
}
